package org.jmc.refmanager.web.wicket.page.panel;

import org.apache.wicket.Component;
import org.apache.wicket.MarkupContainer;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.ajax.markup.html.navigation.paging.AjaxPagingNavigator;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.markup.repeater.data.DataView;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;
import org.jmc.refmanager.domain.dao.QueryParam;
import org.jmc.refmanager.domain.model.Adresse;
import org.jmc.refmanager.domain.model.Adresse.AdressePK;
import org.jmc.refmanager.domain.model.OrgUnit;
import org.jmc.refmanager.domain.model.filter.AdresseFilter;
import org.jmc.refmanager.web.wicket.behavior.DisableEnterKeyBehavior;
import org.jmc.refmanager.web.wicket.provider.AdresseSortableDataProvider;

/**
 */
public abstract class SelectCodePostalPanel2 extends Panel {
	private static final long serialVersionUID = 1L;

	final QueryParam<Adresse> queryParams = new QueryParam<Adresse>();


	/**
	 * Methode que la page principale va implementer la persistance
	 * @param target
	 */
	public abstract void onSave(AjaxRequestTarget target); 

	public abstract void onCancel(AjaxRequestTarget target); 

	
	private final IModel<Adresse> adresseModel;
	
	/**
	 * 
	 * @param id
	 * @param serviceModel
	 */
	public SelectCodePostalPanel2(String id, final IModel<OrgUnit> serviceModel) {
		this(id, new CompoundPropertyModel<Adresse>(new Adresse()), serviceModel);
	}

	/**
	 * 
	 * @param id
	 * @param serviceModel
	 */
	public SelectCodePostalPanel2(String id, final IModel<Adresse> adresseModel, final IModel<OrgUnit> serviceModel) {
		super(id, new CompoundPropertyModel<Adresse>(adresseModel));
		
		setOutputMarkupId(true);
		
		this.adresseModel = adresseModel;
		
		Form<Adresse> form = new Form<Adresse>("searchForm", adresseModel);
		form.setOutputMarkupId(true);
		add(form);
		
		TextField<String> codePostal = new TextField<String>("codePostal");
		codePostal.setOutputMarkupId(true);
		form.add(codePostal);
		
//		Adresse adresse = (Adresse) getDefaultModelObject();
//		queryParams.setCriteriaExample(adresse);
		queryParams.setExcludeProperties(AdresseFilter.filterByCodePostal());

		AdresseSortableDataProvider dp = new AdresseSortableDataProvider(queryParams);
		
		final DataView<Adresse> dataView = new DataView<Adresse>("adresses", dp) {
			private static final long serialVersionUID = 1L;

			@Override
		    public boolean isVisible() {
				return this.getItemCount() > 0;
			}

			@Override
			protected void populateItem(Item<Adresse> item) {
				final Adresse adresse = item.getModelObject();
				MarkupContainer selectLink = new AjaxLink<AdressePK>("selectLink", new PropertyModel<AdressePK>(adresse, "pk")) {
					private static final long serialVersionUID = 1L;

					@Override
					public void onClick(AjaxRequestTarget target) {
						AdressePK pk = getModelObject();
						serviceModel.getObject().setCodePostal(pk.getCodePostal());
						serviceModel.getObject().setInsee(pk.getInsee());
						serviceModel.getObject().setDepartement(adresse.getCodeDepartement());
						serviceModel.getObject().setCommune(adresse.getCommune());
						serviceModel.getObject().setTgDepartement(adresse.getCodeTGDepartement());
						serviceModel.getObject().setDialogDepartement(adresse.getCodeDialogDepartement());
						serviceModel.getObject().setRegion(adresse.getCodeRegion());

						// Reinitialise le modele
						SelectCodePostalPanel2.this.adresseModel.setObject(new Adresse());
						// Supprime le critere de recherche
						queryParams.setCriteriaExample(null);
						
						// Delegation e la methode onSave()
						onSave(target);
					}
				};
				selectLink.add(new Label("codePostal", adresse.getCodePostal()));
				item.add(selectLink);
				
				item.add(new Label("codeInsee", adresse.getInsee()));
				item.add(new Label("commune", adresse.getCommune()));
			}
		};
		
		dataView.setItemsPerPage(20);
		dataView.setOutputMarkupId(true);
		add(dataView);

        final Label noResultLabel = new Label("noResult", "Aucun résultat ne correspond à votre recherche");
        noResultLabel.setVisible(dataView.getItemCount()==0);
        add(noResultLabel);

		AjaxPagingNavigator navigator = new AjaxPagingNavigator("navigator", dataView) {
			private static final long serialVersionUID = 1L;

			@Override
		    public boolean isVisible() {
				noResultLabel.setVisible(dataView.getItemCount()==0);
		        return dataView.getItemCount() > 0;
		    }
		};
		navigator.setOutputMarkupId(true);
		add(navigator);

		// Supprime la soumission du formulaire si on appuie sur "Entree"
		form.visitChildren(FormComponent.class, new IVisitor<Component>() {
			@Override
			public Object component(Component component) {
				if (!(component instanceof Button))
					component.add(new DisableEnterKeyBehavior());

				return IVisitor.CONTINUE_TRAVERSAL;
			} 
		});
		
		form.add(new AjaxButton("btnSearch", form) {
			private static final long serialVersionUID = 1L;

			@Override
			public void onSubmit(AjaxRequestTarget target, Form<?> form) {
				Adresse example = new Adresse();
				example.setCodePostal(form.get("codePostal").getDefaultModelObjectAsString());
				queryParams.setCriteriaExample(example);
				
				// Permet de rafraecher les donnees du panneau
				target.addComponent(SelectCodePostalPanel2.this);
			}
		});
		
		AjaxButton btnCancel = new AjaxButton("btnCancel", form) {
			private static final long serialVersionUID = 1L;

			@Override
			protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
				form.clearInput();
				// Reinitialise le modele
				SelectCodePostalPanel2.this.adresseModel.setObject(new Adresse());
				// Supprime le critere de recherche
				queryParams.setCriteriaExample(null);
				onCancel(target);
			}
		};
		// Pas de validation
		btnCancel.setDefaultFormProcessing(false);
		form.add(btnCancel);
	}
}

